package com.unittec.drainage.provider.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.unittec.drainage.provider.common.ServiceIdConstants;
import com.unittec.drainage.provider.scope.ThreadLocalScope.AuthData;
import com.unittec.drainage.provider.service.HystrixRestTemplateService;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.log.request.Req102017;

/**
 * @author wuxinwei
 */
@Component
public class AsyncAddLog {

    private static final Logger logger = LoggerFactory.getLogger(Log.class);

    /**
     * 添加操作日志
     */
    private static final String ADD_LOG_OPERATE_URL = "http://" + ServiceIdConstants.LOG_SERVER_102 + "/102017";

    @Autowired
    private HystrixRestTemplateService hystrixRestTemplateService;

    @Async("taskExecutor")
    public void asyncAddOperateLog(GatewayRequest<Req102017> gatewayRequest, AuthData authData) {
        try {
            // 调用微服务
            hystrixRestTemplateService.exchange(ADD_LOG_OPERATE_URL, gatewayRequest, authData,
                new ParameterizedTypeReference<Result<String>>() {});
        } catch (RuntimeException e) {
            // 捕获到异常后，在本地记录日志，确保日志信息不会丢失
            logger.error("log content=【{}】 errmsg=【{}】", JSON.toJSONString(gatewayRequest), e.toString(), e);
        }
    }

}
